package client

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"time"
	"zxs-micro-2/zxs-micro-balance-client/config"
	"zxs-micro-2/zxs-micro-balance-client/utils"
	"zxs-micro-2/zxs-micro-proto/balancepb/balance"
)

var conn *grpc.ClientConn
var client balance.BalanceServiceClient

func InitBalanceClient(selfId string) {
	var err error
	conn, err = grpc.Dial(config.Cfg.BalanceServerAddr,
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(
			fmt.Sprintf(`{"HealthCheckConfig": {"ServiceName": "%s"}}`, "grpc.health.v1.Health")))
	if err != nil {
		panic(err)
	}
	client = balance.NewBalanceServiceClient(conn)
	go startBalanceHeartBeats(context.Background(), selfId)
}

//每5秒心跳一次
func startBalanceHeartBeats(ctx context.Context, selfId string) {
	for {
		<-time.After(time.Second * 5)
		client.BalanceHeartBeat(ctx, &balance.BalanceHeartBeatRequest{
			Server: &balance.ServerStruct{
				ServerIpAddr: config.Cfg.SelfIpAddr,
				ServerId:     selfId,
				ServerType:   config.Cfg.ServiceType,
				Load:         utils.CurrentLoad(),
			},
		})
	}
}

func GetBalanceClient() balance.BalanceServiceClient {
	return client
}
